package org.demo;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

public class DemoFilter implements Filter{

	public void destroy() {
	}

	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain filter) throws IOException, ServletException {
		System.out.println("我是拦截器...........");
		
		Map<String, String[]> params = req.getParameterMap();
		//TreeMap:底层是二叉树数据结构，线程不同步，可用于给Map集合中的键进行排序。
        Map<String, String[]> extraParams = new TreeMap<String, String[]>();
        Iterator<String> i = params.keySet().iterator();

        while ( i.hasNext() ){
            String key = (String) i.next();
            String value = ((String[]) params.get( key ))[ 0 ];
            extraParams.put(key.toLowerCase(), new String[] {value});
        }
        extraParams.put("name", new String[] { "嘿嘿。有值了" });
        
        HttpServletRequest wrappedRequest = new CustomWrappedRequest((HttpServletRequest)req, extraParams);

		filter.doFilter(wrappedRequest, resp);
	}

	public void init(FilterConfig arg0) throws ServletException {
		
	}

}
